import json
import logging
from datetime import datetime

import apscheduler
from apscheduler.schedulers.background import BackgroundScheduler
from django.http import JsonResponse
from django.views import View
from django_apscheduler.jobstores import DjangoJobStore, register_events

from lapi_app.models.task_case.task import Task

logger = logging.getLogger('django')
scheduler = BackgroundScheduler()
scheduler.add_jobstore(DjangoJobStore(), 'default')


class Delete_task(View):

    def post(self, request, *args, **kwargs):

        data = json.loads(request.body)
        task_id = data["task_id"]
        if task_id == "":
            return JsonResponse({
                "code": 100,
                "message": "必要参数不可为空"
            })
        elif not Task.objects.filter(id=task_id):
            return JsonResponse({
                "code": 100,
                "message": "删除失败，没有此任务"
            })
        else:
            try:
                task = Task.objects.filter(id=task_id)
                task.delete()
                if scheduler.get_job(job_id=str(task_id)):
                    # 如果存在相同的ID任务，同时删掉
                    scheduler.remove_job(job_id=str(task_id))
                else:
                    pass
                return JsonResponse({
                    "code": 200,
                    "message": "删除任务成功"
                })
            except Exception as e:
                return JsonResponse({
                    "code": 100,
                    "message": "删除任务失败",
                    "Exception": str(e)
                })
